# !/usr/bin/env python
# encoding: utf-8


"""
  @author: gaogao
  @file: DCPDialog.py
  @time: 2022/4/13 16:32
  @desc:
"""

from PyQt5.QtCore import QSize, Qt, QRect, pyqtSignal
from PyQt5.QtGui import QIcon, QBrush, QColor, QPen, QFont, QPainter
from PyQt5.QtWidgets import QWidget, QDialog, QVBoxLayout, QGridLayout, QComboBox, QPushButton, QLabel, QMessageBox
from gui import constant
import json


class DCPDialog(QDialog):
    send_signal = pyqtSignal(object)

    def __init__(self, parent=None):
        super().__init__(parent)
        with open("./static/style_sheet/origin.qss", mode='r', encoding='utf-8') as f:
            style_sheet = f.read()
        self.setStyleSheet(style_sheet)
        self.setWindowTitle("  DCP  DEFINE")
        self.setWindowIcon(QIcon("./static/style_sheet/icons/logo.png"))
        self.resize(400, 600)
        self.vl_dcp = QVBoxLayout(self)
        self.vl_dcp.setContentsMargins(0, 0, 0, 0)
        self.wd_dcp = QWidget()
        self.gl_dcp = QGridLayout(self.wd_dcp)
        row = 0
        for dcp_name in constant.DCP_TITLE:
            cb_dcp = QComboBox()
            cb_dcp.setObjectName(f"cb_dcp{row}")
            cb_dcp.addItems(constant.DCP_TYPES)
            # cb_dcp.setCurrentIndex(current_sub_die_info[row])
            self.gl_dcp.addWidget(QLabel(dcp_name), row, 0)
            self.gl_dcp.addWidget(cb_dcp, row, 1)
            row += 1
        self.pb_submit = QPushButton("提交")
        self.gl_dcp.addWidget(self.pb_submit, 15, 0, 1, 2)
        self.vl_dcp.addWidget(self.wd_dcp)
        self.pb_submit.clicked.connect(self.send_content)

    def _common_save_hsp(self, parent_widget, config_obj, section_head, auto_save_dict):
        # auto_save_list = {"rb": QRadioButton, "le": QLineEdit,
        #                   "cb": QComboBox, "ck": QCheckBox}
        # section_head = main_ui
        # create section
        for tool_head_name in auto_save_dict:
            child_list = parent_widget.findChildren(auto_save_dict[tool_head_name])
            current_section = f"{section_head}/{tool_head_name}"
            config_obj.add_section(current_section)
            for tool_obj in child_list:
                id_name = tool_obj.objectName()
                if "qt_spinbox_lineedit" in id_name or "qt_calendar_yearedit" in id_name or "lbt_title" in id_name or id_name == "":
                    continue
                tool_obj = parent_widget.findChild(auto_save_dict[tool_head_name], id_name)
                if tool_head_name == "rb":
                    raw_value = tool_obj.isChecked()
                elif tool_head_name == "le":
                    raw_value = tool_obj.text()
                elif tool_head_name == "sb":
                    raw_value = tool_obj.value()
                elif tool_head_name == "cb":
                    raw_value = tool_obj.currentIndex()
                elif tool_head_name == "ck":
                    raw_value = tool_obj.isChecked()
                elif tool_head_name == "sw":
                    raw_value = tool_obj.getState()
                config_obj.set(current_section, id_name,
                               raw_value if isinstance(raw_value, str) else json.dumps(raw_value))

    def _common_recall_hsp(self, parent_widget, config_obj):
        auto_save_dict = {f"dcp_settings/cb": QComboBox}
        for section_name in auto_save_dict:  # recall subdie display settings
            for option_name in config_obj.options(section_name):
                tool_obj = parent_widget.findChild(auto_save_dict[section_name], option_name)
                if section_name[-2:] == "rb":
                    tool_obj.setChecked(json.loads(config_obj.get(section_name, option_name)))
                elif section_name[-2:] == "le":
                    tool_obj.setText(config_obj.get(section_name, option_name))
                elif section_name[-2:] == "sb":
                    tool_obj.setValue(json.loads(config_obj.get(section_name, option_name)))
                elif section_name[-2:] == "cb":
                    tool_obj.setCurrentIndex(json.loads(config_obj.get(section_name, option_name)))
                elif section_name[-2:] == "ck":
                    tool_obj.setChecked(json.loads(config_obj.get(section_name, option_name)))
                elif section_name[-2:] == "sw":
                    tool_obj.setState(json.loads(config_obj.get(section_name, option_name)))

    def send_content(self):
        result = self.get_pair_smu_dcp()
        final_result = list(map(self.is_none, result.values()))
        if not any(final_result):
            self.show_critical("警告", "请先设置DCP探针和SMU之间的对应关系")
        else:
            if final_result.count(True) >= 2:
                self.close()
                self.send_signal.emit(result)
            else:
                self.show_critical("警告", "请至少设置两个SMU")

    def is_none(self, value):
        return True if value.strip() != "None" else False

    def get_pair_smu_dcp(self):
        smu_dcp = {}
        for i in range(1, len(self.wd_dcp.children()) - 1, 2):
            if i < len(self.wd_dcp.children()) - 1:
                smu_dcp[self.wd_dcp.children()[i].text()] = self.wd_dcp.children()[i + 1].currentText()
        if all(smu_dcp.values()):
            return smu_dcp

    def show_critical(self, title, content):
        QMessageBox.critical(self, title, content)

    # def closeEvent(self, event) -> None:
    #     self.send_content()
